#include<iostream>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<cstring>

void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt=0;
    while(true)
    {
        buffer[0]=0;
        snprintf(buffer,sizeof(buffer)-1,"我是子进程，我的pid:%d , cnt:%d",getpid(),cnt);
        write(wfd,buffer,strlen(buffer));
        sleep(1);
        cnt++;
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        buffer[0]=0;
        read(rfd,buffer,sizeof(buffer)-1);
        std::cout<<"子进程说："<<buffer<<std::endl;
    }
}

int main()
{
    int fds[2]={0};
    int n=pipe(fds);
    if(n<0)
    {
        std::cerr<<"pipe error"<<std::endl;
    }
    pid_t id=fork();
    if(id==0)
    {
        //关闭不需要的端
        close(fds[0]);
        ChildWrite(fds[1]);

        close(fds[1]);
        exit(0);
    }

    close(fds[1]);
    FatherRead(fds[0]);

    close(fds[0]);
    waitpid(id,NULL,0);
    return 0;
}